package com.vic.controller;

import com.alibaba.fastjson.JSONObject;
import com.vic.common.util.CommonUtil;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@RestController
public class MediaController {
    @ResponseBody
    @RequestMapping(value = "/uploadimg", method = RequestMethod.POST)
    public JSONObject hello(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "editormd-image-file", required = false) MultipartFile attach) {

        JSONObject jsonObject = new JSONObject();

        try {
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
//            String rootPath = request.getSession().getServletContext().getRealPath("/static/img/blog/");
            String rootPath = "data/images";

            System.out.println("editormd上传图片：" + rootPath);

            /**
             * 文件路径不存在则需要创建文件路径
             */
            File filePath = new File(rootPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }

            // 最终文件名
            String filename = attach.getOriginalFilename();
            String pathOut = rootPath + File.separator + filename;

            CommonUtil.ioCopy(attach.getInputStream(), pathOut);
            // 下面response返回的json格式是editor.md所限制的，规范输出就OK

            jsonObject.put("success", 1);
            jsonObject.put("message", "上传成功");
            jsonObject.put("url", "/"+filename);
        } catch (Exception e) {
            jsonObject.put("success", 0);
        }

        return jsonObject;
    }
}
